package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 * 
 * @author alexis
 * @date 2025-11-09
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));

    }

    @Override
    public List<ProductVo> allProduct() {
        //不想转一次的话就在 private RedisTemplate<String,String> redisTemplate 这里写明泛型
        String result = (String) redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty( result)) {
            return new ArrayList<ProductVo>();
        }
        List<ProductVo> list = JSONUtil.toList(result, ProductVo.class);
        return list;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        //判断设备名称和设备标记是否已经存在
        LambdaQueryWrapper<Device> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(Device::getDeviceName,deviceDto.getDeviceName())
                .or().eq(Device::getNodeId,deviceDto.getNodeId());
        long count = count(wrapper);
        if (count>0) {
            throw new BaseException("设备名称或设备标记已存在");
        }

        //判断同一位置是否已经绑定了同产品的设备

        LambdaQueryWrapper<Device> wrapper2= new LambdaQueryWrapper<>();
 wrapper2.eq(Device::getProductKey,deviceDto.getProductKey())
                .eq(Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(Device::getLocationType,deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType());
        long count2 = count(wrapper2);
        if (count2>0) {
            throw new BaseException("同一位置已经绑定了同产品的设备");
        }
        //调用IOT平台接口 完成设备注册
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.withProductId(deviceDto.getProductKey());
        addDevice.withDeviceName(deviceDto.getDeviceName());
        addDevice.withNodeId(deviceDto.getNodeId());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.withSecret(secret);
        addDevice.setAuthInfo(authInfo);
        request.withBody(addDevice);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("调用IOT接口报错");
        }

        //保存设备数据到mysql
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
        device.setIotId(response.getDeviceId());
        device.setSecret( secret);
        save( device);
    }
    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response= client.showDevice(request);

        DeviceDetailVo detailVo = new DeviceDetailVo();
        //属性拷贝
        BeanUtil.copyProperties(device,detailVo);

        detailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setActiveTime(activeTime);
        }

        return detailVo;
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String,Object>>queryServiceProperties(String iotId) {
        List<Map<String,Object>> list = new ArrayList<>();

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        List<DeviceShadowData> shadow = response.getShadow();
        //判断是否获取到了影子数据
        if(CollUtil.isEmpty(shadow)){
           return list;
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        //处理上报时间日期
        LocalDateTime activeTime =  LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("value",v);
            map.put("eventTime",eventTime);
            list.add(map);
        });

        return list;

    }
}

